package com.atguigu.gmall.common.Interceptor;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//@Component
public class FeignInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1号  请求头中的用户ID  传递给 2号
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        //判断
        if(null != requestAttributes) {
            //1号对象
            HttpServletRequest request = requestAttributes.getRequest();
            //真实
            if (null != request) {
                String userId = request.getHeader("userId");
                if (!StringUtils.isEmpty(userId)) {
                    //RequestTemplate : 即将马上发出远程调用请求对象  2号
                    requestTemplate.header("userId", userId);
                }
                String userTempId = request.getHeader("userTempId");
                if (!StringUtils.isEmpty(userTempId)) {
                    //RequestTemplate : 即将马上发出远程调用请求对象  2号
                    requestTemplate.header("userTempId", userTempId);
                }
            }
        }
    }
}
